package com.nsgf.library.domain.request;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;

import com.nsgf.library.utils.DialogController;
import com.nsgf.library.utils.NetworkUtils;
import com.nsgf.library.utils.ToastUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import io.reactivex.ObservableEmitter;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Cancellable;
import retrofit2.HttpException;

/**
 * 显示ProgressDialog的封装
 *
 * @param <T>
 */
public class DisposableObserver<T> implements ObservableEmitter<T> {
    private ProgressDialog progressDialog;
    private HttpOnNextListener<T> listener;
    private Context context;

    public DisposableObserver(HttpOnNextListener<T> onNextListener) {
        this.listener = onNextListener;
    }

    private void showProgressDialog(boolean showProgress) {
        if (showProgress) {
            displayLoading();
        }
    }

    /**
     * 显示loading对话框
     */
    public void displayLoading() {
        displayLoading(null);
    }

    /**
     * 显示带文字的loading对话框
     *
     * @param text 显示的文字
     */
    public void displayLoading(String text) {
        getController().displayLoading(text);
    }


    /**
     * 取消loading对话框
     */
    public void dismissLoading() {
        dismissLoading(false);
    }

    /**
     * 取消loading对话框
     *
     * @param force 是否强制取消:
     *              true    立即dismiss掉loading对话框
     *              false   延迟一定时间{@link Constant#MinLoadingTime}后dismiss
     */
    public void dismissLoading(boolean force) {
        getController().dismissLoading(force);
    }

    protected DialogController dialogController;

    public DialogController getController() {
        if (dialogController == null) {
            dialogController = new DialogController(context);
            dialogController.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    DisposableObserver.this.onComplete();
                }
            });
        }
        return dialogController;
    }


    @Override
    public void onNext(T t) {
        listener.onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        String error = null;
        try {

            if (e instanceof SocketTimeoutException) {//请求超时
            } else if (e instanceof ConnectException) {//网络连接超时
                error = "网络连接超时";
            } else if (e instanceof SSLHandshakeException) {//安全证书异常
                error = "安全证书异常";
            } else if (e instanceof HttpException) {//请求的地址不存在
                int code = ((HttpException) e).code();
                if (code == 504) {
                    error = "网络异常，请检查您的网络状态";
                } else if (code == 404) {
                    error = "请求的地址不存在";
                } else if (code == 408) {
                    error = "手速太快了,请5秒后再试";
                } else {
                    error = "手速太快了,请5秒后再试";
                }
            } else if (e instanceof UnknownHostException) {//域名解析失败
                if (!NetworkUtils.isConnected()) {
                    error = "网络异常，请检查您的网络状态";
                } else
                    error = "域名解析失败";
            } else {
                error = "手速太快了,请5秒后再试";
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            dismissProgressDialog();
            progressDialog = null;
        }
        if (listener != null) {
            listener.onFail(error);
            dismissProgressDialog();
        }
        ToastUtils.showShortToast(error);
    }

    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        progressDialog = null;
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    @Override
    public void setDisposable(Disposable d) {

    }

    @Override
    public void setCancellable(Cancellable c) {

    }

    @Override
    public boolean isDisposed() {
        return false;
    }

    @Override
    public ObservableEmitter<T> serialize() {
        return null;
    }

    @Override
    public boolean tryOnError(Throwable t) {
        return false;
    }
}
